<?php
function game_go(&$arrReturn)
{  
    global $db;
    $speNo = $_GET['no'];
    $isToAuto = true;
    $nowTime = strtotime(date('Y-m-d H:i:s',time()));
    $BeginTime = strtotime(date('Y-m-d',time()) . " 19:10:00");
	$EndTime = strtotime(date('Y-m-d',time()) . " 20:00:00"); 
    
    if($nowTime > $BeginTime && $nowTime < $EndTime)
    {
    	$arrReturn['msg'] = 'not in open game time(can)';
    	return;
	}
    $No = intval($speNo);
    if($speNo == 0)
    {
		$sql = "select gameno from game_result where gametype = 'gamecan' and isopen = 0 order by gameno desc limit 1";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$No = $rs["gameno"];
		}
    	else
    	{ 
    		//保证采集不到但下盘时间快到时自动下注
		    $sql = "SELECT id,kgtime,now() as nowtime FROM gamecan28 WHERE kj = 0 AND zdtz_r = 0 AND kgtime > NOW() ORDER BY kgtime LIMIT 1";
		    $query = $db->query($sql);
		    if($rs = $db->fetch_array( $query ))
		    {
		        $NextNo = $rs['id'];
		        if(strtotime($rs['kgtime']) - strtotime($rs['nowtime']) < 30)
		        {
			        //自动投注
			        AutoPress($arrReturn,$No-1,$NextNo);
				}
		    }
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "no open game record(pk)";
    		$arrReturn['log'] .= LogFormat("no open game record(pk)");
    		return;
		}
    	
    }
    else
    {
    	$isToAuto = false;
		$sql = "SELECT id FROM gamecan28 WHERE kj = 0 and id = '{$No}' ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$No = $rs["id"];
		}
    	else
    	{
    		$arrReturn['msg'] = "{$No} had been opened(can)";
    		$arrReturn['log'] .= LogFormat("{$No} had been opened(can)");
    		return;
		}
    }
    $arrReturn['no'] = $No;
    $strkjNum = GetGameResult($No);
    $kjnum_array = explode( "|", $strkjNum );
	if ( count($kjnum_array) == 20 ) //取到了
	{
		//排序
		sort($kjnum_array,SORT_NUMERIC);
		//更新开奖状态
	    $sql = "update game_result set isopen = 1,opentime = now() where gametype = 'gamecan' and gameno = '{$No}'";
	    $db->query($sql);
	    
		$arrReturn['log'] .= LogFormat("open result string:" . $strkjNum . " (can)");
		$arrReturn['log'] .= LogFormat('begin open time:' . date('Y-m-d H:i:s') . " (can)");
	    //开奖gamecan28
	    $zjh_a = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
	    $zjh_b = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
	    $zjh_c = $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15] + $kjnum_array[18];
	    $zj_a = substr( $zjh_a, -1 );
	    $zj_b = substr( $zjh_b, -1 );
	    $zj_c = substr( $zjh_c, -1 );
	    $zj_result = $zj_a + $zj_b + $zj_c;
		
	   		file_put_contents('1.php',"22",FILE_APPEND);
		/* wk  		*/
		$res = get_kj_gamecan28($No,$zj_a,$zj_b,$zj_c,$zj_result,$strkjNum);
		$arrRet['code'] = $res['dd'][0][0]["result"];
		$arrRet['msg'] = ChangeEncodeG2U( $res['dd'][0][0]["msg"]);
		
		file_put_contents('1.php',"<?php\r\nreturn ".var_export($No,true)."?>",FILE_APPEND);
		// $sql = "call web_kj_gamecan28({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
		// $arr = $db->Mysqli_Multi_Query($sql);
		// $arrRet['code'] = $arr[0][0]["result"];
		// $arrRet['msg'] = ChangeEncodeG2U( $arr[0][0]["msg"]);
		
		$strlog = "gamecan28" . $No . "result is: ({$arrRet['code']})".  " (can)";
		$arrReturn['log'] .= LogFormat($strlog); 
		//开奖gamecan36
	   /* $zjh_a = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
	    $zjh_b = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
	    $zjh_c = $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15] + $kjnum_array[18];
	    $zj_a = substr( $zjh_a, -1 );
	    $zj_b = substr( $zjh_b, -1 );
	    $zj_c = substr( $zjh_c, -1 );
	    $zj_result = GetGame36Result($zj_a,$zj_b,$zj_c);
	    $sql = "call web_kj_gamecan36({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = ChangeEncodeG2U( $arr[0][0]["msg"]);
		$strlog = "gamecan36" . $No . "result is: ({$arrRet['code']})".  " (can)";
		$arrReturn['log'] .= LogFormat($strlog); 
		//开奖gamecan16
		$zjh_a = $kjnum_array[0] + $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15];
	    $zjh_b = $kjnum_array[1] + $kjnum_array[4] + $kjnum_array[7] + $kjnum_array[10] + $kjnum_array[13] + $kjnum_array[16];
	    $zjh_c = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
	    $zj_a = ($zjh_a % 6) + 1;
	    $zj_b = ($zjh_b % 6) + 1;
	    $zj_c = ($zjh_c % 6) + 1;
	    $zj_result = $zj_a + $zj_b + $zj_c;
	    $sql = "call web_kj_gamecan16({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
	    //WriteLog("开奖gamecan16: " . $sql);
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = ChangeEncodeG2U($arr[0][0]["msg"]);
		$strlog = "gamecan16" . $No . "result is: ({$arrRet['code']})".  " (can)";
		$arrReturn['log'] .= LogFormat($strlog); */
		
		//WriteLog($strlog);
		//开奖game11
	/*	$zjh_a = $kjnum_array[0] + $kjnum_array[3] + $kjnum_array[6] + $kjnum_array[9] + $kjnum_array[12] + $kjnum_array[15];
	    $zjh_b = $kjnum_array[2] + $kjnum_array[5] + $kjnum_array[8] + $kjnum_array[11] + $kjnum_array[14] + $kjnum_array[17];
	    $zj_a = ($zjh_a % 6) + 1;
	    $zj_b = ($zjh_b % 6) + 1;
	    $zj_c = -1;
	    $zj_result = $zj_a + $zj_b;
	    $sql = "call web_kj_gamecan11({$No},{$zj_a},{$zj_b},{$zj_c},{$zj_result},'{$strkjNum}')";
	    //WriteLog("开奖gamecan11: " . $sql);
		$arr = $db->Mysqli_Multi_Query($sql);
		$arrRet['code'] = $arr[0][0]["result"];
		$arrRet['msg'] = ChangeEncodeG2U($arr[0][0]["msg"]);
		$strlog = "gamecan11" . $No . "result is: ({$arrRet['code']})".  " (can)";
		$arrReturn['log'] .= LogFormat($strlog); 
		$arrReturn['log'] .= LogFormat('end open time:' . date('Y-m-d H:i:s') . " (can)");*/
	}
	else //取不到结果
	{
		$arrReturn['code'] = 'noreward';
		$arrReturn['msg'] = "no catch {$No} result(can)";
		$arrReturn['log'] = LogFormat("no catch {$No} result!(can)");
		return;
	}
	
	if($isToAuto)
	{
	    //给最新一盘自动投注
	    $NextNo = $No + 1;
	    $randScond = rand(3,5);
	    $sql = "SELECT id,DATE_ADD(NOW(),INTERVAL {$randScond} SECOND) nowtime FROM gamecan28 WHERE kj = 0 and id={$NextNo} limit 1";
	    $query = $db->query($sql);
	    if($rs = $db->fetch_array( $query ))
	    {
	    	$arrReturn['nextid'] = $rs['id'];
	        $arrReturn['nexttime'] = $rs['nowtime'];
	        //自动投注
	        AutoPress($arrReturn,$No,$NextNo);
	    }
	}
    
    
}
function AutoPress(&$arrReturn,$No,$NextNo)
{
	global $db;
	 //gamecan28自动投注
	$sql = "call web_tz_gamecan28_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "gamecan28 " . $NextNo . " auto press(" .$arrT[0][0]["result"] . ")" . " (can)";
	$arrReturn['log'] .= LogFormat($strlog); 
	//gamecan36自动投注
	$sql = "call web_tz_gamecan36_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "gamecan36 " . $NextNo . " auto press(" .$arrT[0][0]["result"] . ")" . " (can)";
	$arrReturn['log'] .= LogFormat($strlog); 
	
	//gamecan16自动投注
	$sql = "call web_tz_gamecan16_auto_new({$No},{$NextNo})";
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "gamecan16 " . $NextNo . " auto press(" .$arrT[0][0]["result"] . ")" . " (can)";
	$arrReturn['log'] .= LogFormat($strlog);
	//gamecan11自动投注
	$sql = "call web_tz_gamecan11_auto_new({$No},{$NextNo})";
	//WriteLog($sql);
	$arrT = $db->Mysqli_Multi_Query($sql);
	$strlog = "gamecan28 " . $NextNo . " auto press(" .$arrT[0][0]["result"] . ")" . " (can)";
	$arrReturn['log'] .= LogFormat($strlog);
	$arrReturn['log'] .= LogFormat('end autopress time:' . date('Y-m-d H:i:s') ." (can)");
}
function GetGame36Result($a,$b,$c)
{
	$arrNum = array($a,$b,$c);
	sort($arrNum);
	if($arrNum[0] == $arrNum[2]) //豹子
		return 1;
	if($arrNum[0] == $arrNum[1] || $arrNum[1] == $arrNum[2]) //对子
		return 2;
	if($arrNum[0] == 0 && ($arrNum[1] == 1 || $arrNum[1]==8) && $arrNum[2] == 9)//顺子特例
		return 3;
	if($arrNum[1] - $arrNum[0] == 1 && $arrNum[2] - $arrNum[1] == 1) //顺子
		return 3;
	if($arrNum[0] == 0  && $arrNum[2] == 9)//半顺特例
		return 4;
	if($arrNum[1] - $arrNum[0] == 1 || $arrNum[2] - $arrNum[1] == 1) //半顺
		return 4;
	return 5; //杂
}
 
function GetGameResult($theNo)
{    
	global $db;
    $ret = "";
    
    $sql = "select gameresult from game_result where gametype='gamecan' and gameno = '{$theNo}' and isopen = 0"; 
    
    $query = $db->query($sql);
    if($rs = $db->fetch_array( $query ))
    {
    	$ret = $rs["gameresult"];
	}
	
	return $ret;
}

error_reporting( 0 );
set_time_limit( 200 );
include_once( "inc/conn.php" );
include_once( "inc/function.php" );
include_once( "inc/kjcan28.php" );
if ( $_GET['key'] == "kj_cantype_result" )
{   
	$arrRet = array('code'=>'ok', //
				    'no' =>'',
				    'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
				    'log'=>'',
				    'nextid'=>'', //下一盘id
				    'nexttime'=>'' //下一篇开奖时间
				    );
    game_go($arrRet);
    if ($arrRet['nextid'] == '')
    { 
    	$RandSecond = rand(3,5);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from gamecan28 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
    }
    //返回
    echo  json_encode($arrRet);
}

$db->close( );
